package com.java.mail;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class JavaMailTest3 {
	public static void main(String[] args) throws Exception{
		test();
	}
	public static void test() throws Exception{
		Properties props = new Properties();
		Session session = Session.getInstance(props);//每次创建一个新的对象
		Message msg = new MimeMessage(session);
		msg.setSubject("这是猪蹄");
		msg.setFrom(new InternetAddress(MimeUtility.encodeText("艾米")+" <Samsara0650@163.com>"));
		msg.setSentDate(new Date());
		//From: =?GBK?B?sKzD1w==?= <Samsara0650@163.com>
		//设置回复人
		msg.setReplyTo(new Address[]{new InternetAddress("ABC@163.com")});
		//设置多个收件人
		msg.setRecipients(RecipientType.TO,InternetAddress.parse(MimeUtility.encodeText("我的163") + " <Samsara0650@163.com>," + MimeUtility.encodeText("我的QQ") + " <935256169@qq.com>"));
		//抄送
		msg.setRecipient(RecipientType.CC, new InternetAddress("Minimalist.life1989@gmail.com"));
		
		MimeMultipart msgMultipart = new MimeMultipart("mixed");//邮件全文（包括正文、附件）
		msg.setContent(msgMultipart);
		MimeBodyPart content = new MimeBodyPart();
		MimeBodyPart attach1 = new MimeBodyPart();
		MimeBodyPart attach2 = new MimeBodyPart();
		msgMultipart.addBodyPart(content);
		msgMultipart.addBodyPart(attach1);
		msgMultipart.addBodyPart(attach2);
		
		DataSource ds1 = new FileDataSource("D:\\temp\\fj1.txt");
		DataHandler dh1 = new DataHandler(ds1);
		attach1.setDataHandler(dh1);
		attach1.setFileName(MimeUtility.encodeText("附件1.txt"));
		
		DataSource ds2 = new FileDataSource("D:\\temp\\fj2.txt");
		DataHandler dh2 = new DataHandler(ds2);
		attach2.setDataHandler(dh2);
		attach2.setFileName("fj2.txt");
		
		MimeMultipart bodyMultipart = new MimeMultipart("related");//邮件正文
		content.setContent(bodyMultipart);//是个复杂体
		MimeBodyPart htmlPart = new MimeBodyPart();
		MimeBodyPart gifPart = new MimeBodyPart();
		bodyMultipart.addBodyPart(htmlPart);
		bodyMultipart.addBodyPart(gifPart);
		
		
		DataSource gifds = new FileDataSource("D:\\temp\\ng.png");
		DataHandler gifdh = new DataHandler(gifds);
		gifPart.setDataHandler(gifdh);
		gifPart.setHeader("Content-Location", "http://www.itcast.cn/logo.gif");
		
		htmlPart.setContent("你们的Java培训真的是最牛的吗？大家都这么说,我想跟你们比试一下！这可是我自己用程序生成和发送的邮件哦！<img src='http://www.itcast.cn/logo.gif'>","text/html;charset=gbk");
		
		msg.saveChanges();
		
		OutputStream ips = new FileOutputStream("D:\\temp\\demo3.eml");
		msg.writeTo(ips);
		ips.close();
		
	}
}
